package com.thymeleaf.study.study_thymeleaf.controller;

import com.thymeleaf.study.study_thymeleaf.pojo.Role;
import com.thymeleaf.study.study_thymeleaf.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by fangjicai on 2020/5/14.
 */

@Controller
public class SimpleController {

    private static final  List<User> list=new ArrayList<>();
    static {
        //模拟数据库查询
        for (int i=0;i<100;i++){
            list.add(new User(i,"name+"+i,10+i,(((i%2)==0)?"男":"女"),"管理员"));
        }
    }

    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(name = "page",defaultValue = "0",required = false) int  page,
                       @RequestParam(name = "pageSize",defaultValue = "5") int pageSize,
                       @RequestParam(name = "keywords",defaultValue = "",required = false) String keywords){
        model.addAttribute("users",list.subList(page*pageSize,page*pageSize+pageSize));
        HashMap<String, Object> pageMap = new HashMap<>();
        pageMap.put("nextPage",(page-1)<0?0:(page-1));
        pageMap.put("curPage",page);
        pageMap.put("prePage",page+1);
        pageMap.put("keywords",keywords);
        model.addAttribute("pageInfo",pageMap);
        return "/simple/list";
    }

    @PostMapping("/delete")
    @ResponseBody
    public String deleteAll(Integer[] ids){
        System.out.println(ids.toString());
        return ids.toString();
    }

    @GetMapping("/add")
    public String add(Model model){
        ArrayList<Role> roles = new ArrayList<>();
        roles.add(new Role("管理员",1));
        roles.add(new Role("超级管理员",2));
        roles.add(new Role("普通人员",3));
        model.addAttribute("roles",roles);
        return "/simple/add";
    }

    @PostMapping("/addUser")
    public String addUser(User user){
        System.out.println(user.toString());
        return "redirect:list";
    }
    @GetMapping("/update")
    public String update(Integer id,Model model){
        System.out.println(id);
        ArrayList<Role> roles = new ArrayList<>();
        roles.add(new Role("管理员",1));
        roles.add(new Role("超级管理员",2));
        roles.add(new Role("普通人员",3));
        model.addAttribute("roles",roles);
        model.addAttribute("user",list.get(id));
        return "/simple/update";

    }

    @PostMapping("/updateUser")
    public String updateUser(User user){
        System.out.println(user.toString());
        return "redirect:list";
    }
}
